#!/usr/bin/env python3
"""
Simple Integration Test
简单的集成测试 - 验证核心功能正常工作
"""

import asyncio
import sys
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from src.media_create.core.config import settings
from src.media_create.core.database import check_db_connection, get_db_stats
from src.media_create.core.cache import cache_manager
from src.media_create.core.task_queue import task_queue
from src.media_create.services.system_monitoring_service import SystemMonitoringService
from src.media_create.services.user_service import UserService
from src.media_create.services.ai_model_service import AIModelService


async def test_basic_imports():
    """测试基本导入"""
    print("🔄 测试基本导入...")
    
    try:
        # 测试配置
        print(f"✅ 配置加载成功: {settings.app_name} v{settings.app_version}")
        
        # 测试数据库连接
        print("🔄 测试数据库连接...")
        db_connected = await check_db_connection()
        if db_connected:
            print("✅ 数据库连接成功")
            db_stats = await get_db_stats()
            print(f"📊 数据库统计: {db_stats}")
        else:
            print("⚠️  数据库连接失败，使用默认配置")
        
        # 测试缓存系统
        print("🔄 测试缓存系统...")
        cache = cache_manager.create_cache(
            "test_cache",
            default_ttl=60,
            max_size=100
        )
        await cache_manager.start_all()
        print("✅ 缓存系统启动成功")
        
        # 测试任务队列
        print("🔄 测试任务队列...")
        await task_queue.start()
        print("✅ 任务队列启动成功")
        
        # 测试AI模型服务
        print("🔄 测试AI模型服务...")
        ai_service = AIModelService()
        print(f"✅ AI模型服务初始化成功，提供商: {list(ai_service.providers.keys())}")
        
        # 测试系统监控服务
        print("🔄 测试系统监控服务...")
        from src.media_create.core.database import DatabaseSession
        db_session = DatabaseSession()
        monitoring_service = SystemMonitoringService(db_session)
        print("✅ 系统监控服务初始化成功")
        
        # 测试用户服务
        print("🔄 测试用户服务...")
        user_service = UserService(db_session)
        print("✅ 用户服务初始化成功")
        
        print("\n🎉 所有核心组件测试通过！")
        return True
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False


async def test_cache_functionality():
    """测试缓存功能"""
    print("\n🔄 测试缓存功能...")
    
    try:
        cache = cache_manager.get_cache("test_cache")
        
        # 测试设置和获取
        await cache.set("test_key", "test_value", ttl=30)
        value = await cache.get("test_key")
        
        if value == "test_value":
            print("✅ 缓存设置/获取功能正常")
        else:
            print(f"❌ 缓存值不匹配: 期望 'test_value', 实际 '{value}'")
            return False
        
        # 测试过期
        await cache.set("expire_key", "expire_value", ttl=1)
        await asyncio.sleep(2)
        expired_value = await cache.get("expire_key")
        
        if expired_value is None:
            print("✅ 缓存过期功能正常")
        else:
            print(f"❌ 缓存过期失败: {expired_value}")
            return False
        
        # 测试统计
        stats = await cache.get_stats()
        print(f"📊 缓存统计: {stats}")
        
        return True
        
    except Exception as e:
        print(f"❌ 缓存测试失败: {e}")
        return False


async def test_task_queue_functionality():
    """测试任务队列功能"""
    print("\n🔄 测试任务队列功能...")
    
    try:
        # 定义测试任务
        async def test_task(task_data):
            print(f"📝 执行任务: {task_data}")
            await asyncio.sleep(0.1)  # 模拟耗时操作
            return f"任务完成: {task_data}"
        
        # 提交任务
        task_id = await task_queue.submit_task(
            test_task,
            args=("测试数据",),
            priority=5
        )
        
        print(f"✅ 任务提交成功: ID={task_id}")
        
        # 检查任务状态
        task = await task_queue.get_task_status(task_id)
        print(f"📋 任务状态: {task.status.value}")
        
        # 等待任务完成
        await asyncio.sleep(0.5)
        
        # 再次检查状态
        task = await task_queue.get_task_status(task_id)
        print(f"📋 任务最终状态: {task.status.value}")
        
        return True
        
    except Exception as e:
        print(f"❌ 任务队列测试失败: {e}")
        return False


async def test_ai_service_functionality():
    """测试AI服务功能"""
    print("\n🔄 测试AI服务功能...")
    
    try:
        ai_service = AIModelService()
        
        # 测试健康检查
        health_status = await ai_service.health_check()
        print(f"🏥 AI服务健康状态: {health_status}")
        
        # 测试模型信息
        if ai_service.providers:
            provider_name = list(ai_service.providers.keys())[0]
            model_info = ai_service.providers[provider_name].get_model_info()
            print(f"📋 模型信息: {model_info}")
        
        print("✅ AI服务功能测试通过")
        return True
        
    except Exception as e:
        print(f"❌ AI服务测试失败: {e}")
        return False


async def cleanup():
    """清理资源"""
    print("\n🧹 清理资源...")
    try:
        await cache_manager.stop_all()
        await task_queue.stop()
        print("✅ 资源清理完成")
    except Exception as e:
        print(f"⚠️  清理警告: {e}")


async def main():
    """主测试函数"""
    print("🚀 Media Create GUI - 最终集成测试")
    print("=" * 50)
    
    test_results = []
    
    try:
        # 运行各项测试
        test_results.append(await test_basic_imports())
        test_results.append(await test_cache_functionality())
        test_results.append(await test_task_queue_functionality())
        test_results.append(await test_ai_service_functionality())
        
        # 计算通过率
        passed_tests = sum(test_results)
        total_tests = len(test_results)
        success_rate = (passed_tests / total_tests) * 100
        
        print("\n" + "=" * 50)
        print(f"📊 测试结果统计:")
        print(f"   通过测试: {passed_tests}/{total_tests}")
        print(f"   成功率: {success_rate:.1f}%")
        
        if success_rate >= 75:
            print("🎉 系统集成测试通过！")
            print("✅ 项目已准备好进行生产部署")
        else:
            print("⚠️  部分测试失败，建议修复后再部署")
            
    except Exception as e:
        print(f"\n❌ 测试执行失败: {e}")
        import traceback
        traceback.print_exc()
        
    finally:
        await cleanup()
    
    return all(test_results)


if __name__ == "__main__":
    success = asyncio.run(main())
    sys.exit(0 if success else 1)